package cn.kimoon.dau_android;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.HashMap;
import java.util.Map;

import cn.kimoon.dau_android.API.ApiDAU;
import cn.kimoon.dau_android.API.AppClient;
import cn.kimoon.dau_android.Dialog.DialogManager;
import cn.kimoon.dau_android.Dialog.LoadingDialog;
import cn.kimoon.dau_android.Model.ModelEngineDetail;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiangdong on 2016/11/23.
 */

public class MonitorDetailActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener,
        View.OnClickListener{
    private RadioButton humitureRB;
    private RadioButton warningRB;
    private RadioButton electricityRB;
    private RadioButton controlRB;

    private ViewPager viewPager;
    private MonitorFragmentPagerAdapter adapter;
    private AVLoadingIndicatorView loadingView;
    private Button refreshBtn;

    private RelativeLayout emptyLayout;

    private ModelEngineDetail engineDetail;
    private int collectorId;
    private String collectorName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitor_detail);

        initLogicData();
        initSubViews();
    }

    private void initLogicData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        collectorId = bundle.getInt("collectorId");
        collectorName = bundle.getString("collectorName");
    }

    private void initSubViews() {
        TextView textView = (TextView) findViewById(R.id.monitor_title_text_view);
        textView.setText(collectorName);

        Button backButton = (Button) findViewById(R.id.monitor_back_button);
        backButton.setOnClickListener(this);

        RadioGroup tabRadioGroup = (RadioGroup) findViewById(R.id.monitor_tab_radio_group);
        humitureRB = (RadioButton) findViewById(R.id.humiture_radio_button);
        warningRB = (RadioButton) findViewById(R.id.warning_radio_button);
        electricityRB = (RadioButton) findViewById(R.id.electricity_radio_button);
        controlRB = (RadioButton) findViewById(R.id.control_radio_button);
        tabRadioGroup.setOnCheckedChangeListener(this);

        viewPager = (ViewPager) findViewById(R.id.view_pager);
//        adapter = new MonitorFragmentPagerAdapter(getSupportFragmentManager());
//        viewPager.setAdapter(adapter);
//        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(this);
        viewPager.setOffscreenPageLimit(3); //设置缓存

        loadingView = (AVLoadingIndicatorView) findViewById(R.id.monitor_indicator_view);

        refreshBtn = (Button) findViewById(R.id.monitor_refresh_button);
        refreshBtn.setOnClickListener(this);

        emptyLayout = (RelativeLayout) findViewById(R.id.empty_bg_view);

        // 网络请求
        requestMonitorDetail();
    }

    // 刷新界面
    private void refreshWholeView() {
        if (adapter == null) {
            adapter = new MonitorFragmentPagerAdapter(getSupportFragmentManager());
            viewPager.setAdapter(adapter);
        }
//        MonitorFragmentPagerAdapter monitorFm = new MonitorFragmentPagerAdapter(getSupportFragmentManager());
        int curIndex = viewPager.getCurrentItem();
        System.out.println("请求返回的数据" + engineDetail.result);
        adapter.updateLogicData(engineDetail.result);
        System.out.println("刷新完数据返回的温度上限:" + engineDetail.result.temperature_secure_line_upper);
//        viewPager.setAdapter(monitorFm);
//        viewPager.setCurrentItem(curIndex);
//        humitureRB.setChecked(true);
        onPageScrollStateChanged(2);    //按钮相对应的改变
    }

    // 按键点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.monitor_back_button:
                backToSuperActivity();
                break;
            case R.id.monitor_refresh_button:
                refreshBtnTapped();
                break;
        }
    }

    //RadioGroup点击响应
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.humiture_radio_button:
                viewPager.setCurrentItem(0);
                break;
            case R.id.warning_radio_button:
                viewPager.setCurrentItem(1);
                break;
            case R.id.electricity_radio_button:
                viewPager.setCurrentItem(2);
                break;
            case R.id.control_radio_button:
                viewPager.setCurrentItem(3);
                break;
        }
    }

    //ViewPager的接口
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //state的状态有三个，0表示什么都没做，1正在滑动，2滑动完毕
        if (state == 2) {
            switch (viewPager.getCurrentItem()) {
                case 0:
                    humitureRB.setChecked(true);
                    break;
                case 1:
                    warningRB.setChecked(true);
                    break;
                case 2:
                    electricityRB.setChecked(true);
                    break;
                case 3:
                    controlRB.setChecked(true);
                    break;
            }
        }
    }

    // 返回上一级
    private void backToSuperActivity() {
        finish();
    }

    // 刷新按钮点击事件
    private void refreshBtnTapped() {
        requestMonitorDetail();
    }

    // 刷新动画
    private void startRefreshAnimation(Boolean isRefresh) {
        if (isRefresh) {
            refreshBtn.setVisibility(View.INVISIBLE);
            loadingView.show();
        } else {
            loadingView.hide();
            refreshBtn.setVisibility(View.VISIBLE);
        }
    }

    // 是否显示无数据提示
    private void emptyLayoutShow(boolean show) {
        emptyLayout.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    // 网络请求
    private void requestMonitorDetail() {
        startRefreshAnimation(true);

        Map<String, String> parameters = new HashMap<>();
        parameters.put("id", Integer.toString(collectorId));

        ApiDAU apiDAU = AppClient.retrofit().create(ApiDAU.class);
        Call<ModelEngineDetail> call = apiDAU.apiCollector(parameters);
        call.enqueue(new Callback<ModelEngineDetail>() {
            @Override
            public void onResponse(Call<ModelEngineDetail> call, Response<ModelEngineDetail> response) {
                startRefreshAnimation(false);
                if (response.body() != null && response.body().errCode == 200) {
                    engineDetail = response.body();
                    emptyLayoutShow(false);
                    refreshWholeView();
                } else {
                    emptyLayoutShow(true);
                    String msg = (response.body() == null ? response.message() : response.body().msg);
                    Toast.makeText(MonitorDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ModelEngineDetail> call, Throwable t) {
                startRefreshAnimation(false);
                emptyLayoutShow(true);
                Toast.makeText(MonitorDetailActivity.this, R.string.internet_request_failed, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
